//
//  BLApplePurchasingManager.swift
//  Runner
//
//  Created by apple on 2020/7/18.
//

import UIKit
import StoreKit

class BLApplePurchasingManager: NSObject {
    
    //跟原生通信
    var channel: FlutterMethodChannel
    
    init(channel: FlutterMethodChannel) {
        
        self.channel = channel
        super.init()
        
        // 监听购买,如果有未完成的订单将会自动执行并回调 paymentQueue:updatedTransactions:方法
        SKPaymentQueue.default().add(self) // 4.设置支付服务
        
        cancelOldPurches()
        
        print("call init")
        
    }
    
    
    ///移除
    deinit {
        SKPaymentQueue.default().remove(self)
        print("call deinit")
    }
    

   //取消之前未完成的内购支付流程
   private func cancelOldPurches(){
      
       let transactions = SKPaymentQueue.default().transactions
       for oldTran in transactions {
           print("取消旧的支付：\(oldTran.payment.productIdentifier)")
           if oldTran.transactionState == SKPaymentTransactionState.purchased ||
               oldTran.transactionState == SKPaymentTransactionState.failed {
               SKPaymentQueue.default().finishTransaction(oldTran)
           }
           
       }
   }
   
   ///开始购买
    func starBuyToAppStore(productId: String){    //需要传入商品id
        print("call starBuyToAppStore")
          
        if SKPaymentQueue.canMakePayments() {
            self.getProductInfo(productId: productId) //充值金额
        }else{
            onPayError(errMsg: "您的手机没有打开程序内付费购买功能")
        }
    }
       
   /**
    * 下面的ProductId应该是事先在itunesConnect中添加好的，已存在的付费项目。否则查询会失败。
    */
   func getProductInfo(productId:String){
       print("call getProductInfo: \(productId)")
       let productIdentifiers = Set<String>([productId])
       let productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
       productsRequest.delegate = self
       productsRequest.start()
   }
    
    //支付失败
    func onPayError(errMsg: String) {
        channel.invokeMethod("onPayError", arguments: errMsg)
    }
    
    //完成上次购买
    func onFinishLastTransaction() {
        channel.invokeMethod("onFinishLastTransaction", arguments: nil)
    }
    
    //完成支付 二次验证
    func onCompleteTransaction(params: Dictionary<String, Any>) {
        channel.invokeMethod("onCompleteTransaction", arguments: params)
    }
    
    
}

extension BLApplePurchasingManager:SKProductsRequestDelegate,SKPaymentTransactionObserver{
   
    ///查询的回调函数
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        print("productsRequest \(response.products)")
        let myProduct = response.products
        if myProduct.count == 0 {
            onPayError(errMsg: "获取商品信息失败")
            return
        }
        ///调起支付框
        let payment = SKMutablePayment(product: myProduct[0])
        SKPaymentQueue.default().add(payment)
    }
    
    
    ///用户购买的操作结果
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        
        print("paymentQueue")
        
        for transaction in transactions {
            print("商品 id: \(transaction.payment.productIdentifier)")
            switch transaction.transactionState {
            case .purchased: ///交易完成
                print("paymentQueue purchased")
                completeTransaction(transaction: transaction)
                break
            case .failed: ///交易失败
                print("paymentQueue failed")
                failedTransaction(transaction: transaction)
                break
            case .restored: ///已购买
                print("paymentQueue restored")
                restoreTransaction(transaction: transaction)
                break
            case .purchasing: ///商品添加进列表
                print("paymentQueue purchasing")
                break
            default:
                print("paymentQueue default")
                break
            }
        }
    }
    
    /**
    * 交易完成  后台二次验证充值
    */
    func completeTransaction( transaction:SKPaymentTransaction){
        
        print("completeTransaction \(transaction)")
        
        let productIdentifier = transaction.payment.productIdentifier
    
        do {
            
            ///验证字符串
            let receipt = try Data(contentsOf: Bundle.main.appStoreReceiptURL!).base64EncodedString(options: .lineLength64Characters)
            
            var param = [:] as [String : Any]
            //param["userId"] = USERINFO.userId()  //用户主键
            param["appleReceipt"] = receipt      //验证字符串
            param["tradeId"] =  productIdentifier          //商品id
            param["transactionId"] = transaction.transactionIdentifier     //苹果订单号
            //二次验证回调
            onCompleteTransaction(params: param)
            //移除transaction购买操作
            SKPaymentQueue.default().finishTransaction(transaction)

        } catch {
            print("异常: \(error)")
        }
    }
    
    
    /**
    * 交易失败
    */
    
    func request(_ request: SKRequest, didFailWithError error: Error) {
        print(error)
        onPayError(errMsg: "交易失败")
        print("didFailWithError")
    }
    
    func failedTransaction( transaction:SKPaymentTransaction){
        if transaction.error != nil {
//            BLTool.showMsg(Text: "用户取消购买")
            onPayError(errMsg: "取消购买")
        } else {
//            BLTool.showMsg(Text: "购买失败")
            onPayError(errMsg: "购买失败")
        }

        SKPaymentQueue.default().finishTransaction(transaction)
        print("failedTransaction")

    }
    
    /**
    * 对于已购商品，处理恢复购买的逻辑
    */
    func restoreTransaction( transaction:SKPaymentTransaction){
        print("restoreTransaction")
        SKPaymentQueue.default().finishTransaction(transaction)
       onFinishLastTransaction()
    }
    
    
}
